package com.app.community.service;

import com.app.community.dto.PersonDTO;
import com.app.community.dto.QuestionDTO;
import com.app.community.model.entity.Question;
import com.app.community.mapper.IndexMapper;
import com.app.community.model.entity.User;
import com.github.pagehelper.PageHelper;
import com.huaban.analysis.jieba.JiebaSegmenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * index页面的逻辑层
 * 2020/10/10 20:15
 **/
@Slf4j
@Service
public class IndexService {
    @Autowired
    IndexMapper indexMapper;

    @Autowired
    CommentService commentService;

    /**
     * 根据页号查询Question
     */
    @Cacheable(cacheNames = {"questionList"},key="#page")
    public List<QuestionDTO> selectQuestionDTO(int page){
        // 分页插件,每页最多十条
        PageHelper.offsetPage((page -1 )* 10,page*10,true);
        return  indexMapper.selectQuestionDTO();
    }

    /**
     * 根据搜索框查询Question
     */
    public List<QuestionDTO> searchQuestionDTO(String search,int page){
        JiebaSegmenter segment = new JiebaSegmenter();
//        根据search生成查询关键字
        StringBuilder tags = new StringBuilder();
        List<String> material = segment.sentenceProcess(search);
        for (int i = 0; i < material.size(); i++) {
            // 替换特殊字符，不能在mysql中检索
            String temp = material.get(i).replaceAll("[\\pP+~$`^=|<>～｀＄＾＋＝｜＜＞￥×]", " ");
            if (i != material.size() - 1) {
                tags.append(temp);
                tags.append("|");
            }else{
                tags.append(temp);
            }
        }

        // 分页插件,每页最多十条
        PageHelper.offsetPage((page -1 )* 10,page*10,true);
        return indexMapper.searchQuestionDTO(tags.toString());
    }

    /**
     * 问题数量
     */
    public Integer selectQuestionCount(){
        return indexMapper.selectQuestionCount();
    }


}
